package com.tanhua.management.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.dubbo.server.api.MessagesApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Album;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Messages;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.management.mapper.UserInfoMapper;
import com.tanhua.management.vo.CommentsVo;
import com.tanhua.management.vo.MessagesVo;
import com.tanhua.management.vo.PageResult;
import com.tanhua.management.pojo.UserInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.tanhua.management.vo.TotalsVo;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MessagesService {

    @Reference(version = "1.0.0")
    private MessagesApi messagesApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 查询用户参与的动态
     *
     * @param userId
     * @param page
     * @param pageSize
     * @param sortProp  排序字段
     * @param sortOrder 升序还是降序
     * @return
     */
    public PageResult queryMessagesList(Integer page, Integer pageSize,
                                        String sortProp, String sortOrder,
                                        String id, String userId, Long sd, Long ed, String state) {
        /*
        先区分查询的是用户所参与的动态列表,还是所有的动态列表(根据用户id查,一定时间内查)
        先判断messagesId,sd,ed,state是否为空,如果messageId不为空,则是根据消息id查询
         */
        //如果userId有值且用户id为空,则查询的是用户所参与的动态列表(消息翻页)

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setPages(0);

        if (userId != null) {
            //查询用户所参与的动态列表
            //从dubbo获取pageInfo对象
            PageInfo<Messages> pageInfo = this.messagesApi.queryMessagesList(userId, page, pageSize,
                    sortProp, sortOrder);
            List<Messages> messagesList = pageInfo.getRecords();

            if (CollectionUtils.isEmpty(messagesList)) {
                return pageResult;
            }

            //通过userId 查询userInfo
            List<Long> userIds = new ArrayList<>();
            for (Messages messages : messagesList) {
                userIds.add(messages.getUserId());
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("user_id", userIds);
            //查询数据总条数
            Integer count = this.userInfoMapper.selectCount(queryWrapper);
            List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

            //填充MessagesVo对象
            List<MessagesVo> messagesVoList = new ArrayList<>();
            for (Messages messages : messagesList) {
                for (UserInfo userInfo : userInfoList) {
                    if (userInfo.getUserId() == messages.getUserId()) {
                        MessagesVo messagesVo = new MessagesVo();

                        messagesVo.setId(messages.getPublishId().toHexString());

                        messagesVo.setNickname(userInfo.getNickName());
                        messagesVo.setUserId(messages.getUserId());
                        messagesVo.setUserLogo(userInfo.getLogo());
                        messagesVo.setText(messages.getText());
                        messagesVo.setState(messages.getState().toString());

                        messagesVo.setReportCount(messages.getReportCount());
                        messagesVo.setLikeCount(messages.getLikeCount());
                        messagesVo.setCommentCount(messages.getCommentCount());
                        messagesVo.setForwardingCount(messages.getForwardingCount());
                        messagesVo.setCreateDate(messages.getCreateDate());
                        List<String> medias = messages.getMedias();
                        String[] array = medias.toArray(new String[medias.size()]);
                        messagesVo.setMedias(array);

                        messagesVoList.add(messagesVo);
                    }
                }
            }

            pageResult.setCounts(count);
            pageResult.setItems(messagesVoList);

            return pageResult;
        } else {
            /*
            如果id为空  根据sd与ed来查询所有动态表,
            id不为空,根据sd与ed来查询该用户id的动态
             */
            //Criteria.where("key1").ne("").ne(null)查询某个字段不为空
            if (StringUtils.isEmpty(id)) {
                //PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
                //Query query = new Query().with(pageRequest);

                List<Publish> publishList = this.mongoTemplate.find(Query.query(Criteria.where("userId").ne("").ne(null)), Publish.class);
                //返回所有的动态数据 与时间进行比较 ,根据时间来获取动态数据
                MessagesService.filterByTime(sd, ed, publishList);

                //更新publish表State的值
                for (Publish publish : publishList) {
                    if(StringUtils.isEmpty(publish.getState())){
                        publish.setState("3");

                    }
                }

                //封装pageResult
                List<Long> userIds = new ArrayList<>();
                for (Publish publish : publishList) {
                    userIds.add(publish.getUserId());
                }
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.in("user_id", userIds);
                //查询数据总条数
                Integer count = this.userInfoMapper.selectCount(queryWrapper);

                List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

                List<MessagesVo> messagesVoList = new ArrayList<>();
                List<TotalsVo> totalsVoList = new ArrayList<>();
                //封装TotalsVo对象
                totalsVoList.add(new TotalsVo("全部", "all", Long.valueOf(publishList.size())));
                totalsVoList.add(new TotalsVo("待审核", "3", this.mongoTemplate.count(Query.query(Criteria.where("state").is(3)), Messages.class)));
                totalsVoList.add(new TotalsVo("已通过", "4", this.mongoTemplate.count(Query.query(Criteria.where("state").is(5)), Messages.class)));
                totalsVoList.add(new TotalsVo("已驳回", "5", this.mongoTemplate.count(Query.query(Criteria.where("state").is(4)), Messages.class)));


                for (Publish publish : publishList) {
                    for (UserInfo userInfo : userInfoList) {
                        if (userInfo.getUserId().longValue() == publish.getUserId().longValue()) {
                            MessagesVo messagesVo = new MessagesVo();
                            /*TotalsVo totalsVo = new TotalsVo();*/

                            messagesVo.setId(publish.getId().toString());
                            messagesVo.setNickname(userInfo.getNickName());
                            messagesVo.setUserId(userInfo.getUserId());
                            messagesVo.setUserLogo(userInfo.getLogo());
                            messagesVo.setText(publish.getText());

                            messagesVo.setState(publish.getState());

                            messagesVo.setReportCount(0);
                            messagesVo.setLikeCount(0);
                            messagesVo.setCommentCount(0);
                            messagesVo.setForwardingCount(0);
                            messagesVo.setCreateDate(publish.getCreated());

                            List<String> medias = publish.getMedias();
                            String[] array = medias.toArray(new String[medias.size()]);
                            messagesVo.setMedias(array);
                            messagesVoList.add(messagesVo);
                        }
                    }

                }
                pageResult.setCounts(count);
                pageResult.setItems(messagesVoList);
                pageResult.setTotals(totalsVoList);

                return pageResult;
            }
        }

        //根据用户id获取所有的动态数据
        PageInfo<Publish> publishPageInfo = this.quanZiApi.queryAlbumList(Long.valueOf(id).longValue(), page, pageSize);
        List<Publish> publishList = publishPageInfo.getRecords();
        //返回所有的动态数据 与时间进行比较 ,根据时间来获取动态数据
        MessagesService.filterByTime(sd, ed, publishList);

        //封装pageResult
        List<Long> userIds = new ArrayList<>();
        for (Publish publish : publishList) {
            userIds.add(publish.getUserId());
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id", userIds);
        //查询数据总条数
        Integer count = this.userInfoMapper.selectCount(queryWrapper);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<MessagesVo> messagesVoList = new ArrayList<>();
        List<TotalsVo> totalsVoList = new ArrayList<>();

        //封装TotalsVo对象
        totalsVoList.add(new TotalsVo("全部", "all", Long.valueOf(publishList.size())));
        totalsVoList.add(new TotalsVo("待审核", "3", this.mongoTemplate.count(Query.query(Criteria.where("state").is(3)), Messages.class)));
        totalsVoList.add(new TotalsVo("已通过", "4", this.mongoTemplate.count(Query.query(Criteria.where("state").is(5)), Messages.class)));
        totalsVoList.add(new TotalsVo("已驳回", "5", this.mongoTemplate.count(Query.query(Criteria.where("state").is(4)), Messages.class)));


        for (Publish publish : publishList) {
            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getUserId().longValue() == publish.getUserId().longValue()) {
                    MessagesVo messagesVo = new MessagesVo();

                    messagesVo.setId(publish.getId().toHexString());
                    messagesVo.setNickname(userInfo.getNickName());
                    messagesVo.setUserId(userInfo.getUserId());
                    messagesVo.setUserLogo(userInfo.getLogo());
                    messagesVo.setText(publish.getText());
                    messagesVo.setState(publish.getState());

                    messagesVo.setReportCount(0);
                    messagesVo.setLikeCount(0);
                    messagesVo.setCommentCount(0);
                    messagesVo.setForwardingCount(0);
                    messagesVo.setCreateDate(publish.getCreated());

                    List<String> medias = publish.getMedias();
                    String[] array = medias.toArray(new String[medias.size()]);
                    messagesVo.setMedias(array);
                    messagesVoList.add(messagesVo);

                }
            }

        }
        pageResult.setCounts(count);
        pageResult.setItems(messagesVoList);
        pageResult.setTotals(totalsVoList);

        return pageResult;
    }


    /*
    返回所有的动态数据 与时间进行比较 ,根据时间来获取动态数据
     */
    private static void filterByTime(Long sd, Long ed, List<Publish> publishList) {
        //
        for (Publish publish : publishList) {
            if (publish.getCreated() < sd && publish.getCreated() > ed) {
                publishList.remove(publish);
            }
        }
    }

    /**
     * 查询单个用户参与动态的具体信息
     *
     * @param publishId
     * @return
     */
    public MessagesVo queryMessagesById(String publishId) {
        MessagesVo messagesVo = new MessagesVo();
        Messages messages = this.messagesApi.queryMessagesById(publishId);
        if (messages == null) {
            //没查到
            return messagesVo;
        }
        //获取userId得到userinfo对象,对MessageVo进行封装
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(messages.getUserId());

        messagesVo.setId(ObjectId.get().toHexString());
        messagesVo.setNickname(userInfo.getNickName());
        messagesVo.setUserId(userInfo.getUserId());
        messagesVo.setUserLogo(userInfo.getLogo());
        messagesVo.setCreateDate(messages.getCreateDate());
        messagesVo.setText(messages.getText());
        messagesVo.setState(messages.getState().toString());
        messagesVo.setTopState(messages.getTopState());
        messagesVo.setReportCount(messages.getReportCount());
        messagesVo.setLikeCount(messages.getLikeCount());
        messagesVo.setCommentCount(messages.getCommentCount());
        messagesVo.setForwardingCount(messages.getForwardingCount());

        List<String> medias = messages.getMedias();
        String[] array = medias.toArray(new String[medias.size()]);
        messagesVo.setMedias(array);

        return messagesVo;
    }

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    /**
     * 查询一个动态的评论具体信息
     *
     * @param publishId
     * @param page
     * @param pageSize
     * @param prop
     * @param sortProp
     * @return
     */
    public PageResult queryCommentsList(String publishId, Integer page, Integer pageSize, String prop, String sortProp) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //根据动态id查询评论表
        PageInfo<Comment> commentPageInfo = this.quanZiApi.queryCommentList(publishId, page, pageSize,prop,sortProp);
        if (CollectionUtils.isEmpty(commentPageInfo.getRecords())) {
            return pageResult;
        }
        //封装返回数据
        List<CommentsVo> commentsVoList = new ArrayList<>();
        List<Comment> commentList = commentPageInfo.getRecords();

        List<Long> userIds = new ArrayList<>();
        for (Comment comment : commentList) {
            userIds.add(comment.getUserId());
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        for (Comment comment : commentList) {
            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getUserId().longValue() == comment.getUserId().longValue()) {
                    CommentsVo commentsVo = new CommentsVo();

                    commentsVo.setId(ObjectId.get().toHexString());
                    commentsVo.setNickname(userInfo.getNickName());
                    commentsVo.setUserId(userInfo.getUserId().toString());
                    commentsVo.setContent(comment.getContent());
                    commentsVo.setCreateDate((int) comment.getCreated().longValue());

                    commentsVoList.add(commentsVo);
                }
            }
        }

        pageResult.setCounts(commentsVoList.size());
        pageResult.setItems(commentsVoList);
        return pageResult;
    }

   /* *//**
     * 更改置顶
     *
     * @param
     * @param
     * @return
     *//*
    public String updateTopStateById(String messagesId, String top) {
        boolean bool = this.messagesApi.updateTopStateById(messagesId, top);
        String message = null;
        if (bool) {
            return message = "操作成功";
        }
        return message;
    }*/


    /*
    审核通过
     */
    public Long passMessages(ArrayList<String> publishIds) {
        Update update = Update.update("state","5");
        Long count=0L;
        for (String publishId : publishIds) {
            count =count+this.mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(publishId)), update, Publish.class).getModifiedCount();
        }
        return count;
    }

    /*
    审核不通过
     */
    public Long rejectMessages(ArrayList<String> publishIds) {
        Update update = Update.update("state","4");
        Long count=0L;
        for (String publishId : publishIds) {
            count =count+this.mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(publishId)), update, Publish.class).getModifiedCount();
        }
        return count;
    }
    /*
    审核撤销
     */
    public Long revocationMessages(ArrayList<String> publishIds) {
        Update update = Update.update("state","3");
        Long count=0L;
        for (String publishId : publishIds) {
            count =count+this.mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(publishId)), update, Publish.class).getModifiedCount();
        }
        return count;
    }
}
